<template>
    <div class="post-edit-component">
        <h2>修改动态</h2>
        <el-form ref="postForm" :model="postForm" label-width="80px">

            <el-form-item label="标题">
                <el-input v-model="postForm.title" class="title-input" maxlength="30" show-word-limit></el-input>
            </el-form-item>

            <el-form-item label="内容">
                <el-input type="textarea" rows="8" resize="none" v-model="postForm.content"></el-input>
            </el-form-item>

            <el-form-item label="图片">
                <el-upload action="#" list-type="picture-card" :limit="countLimit" :file-list="postForm.fileList"
                    :on-change="handlePictureChange" :on-remove="handleRemove" :auto-upload="false" multiple>
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitEditPost">修改</el-button>
                <el-button @click="cancelEdit">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { ElForm, ElFormItem, ElInput, ElButton, ElUpload, ElMessage, ElNotification,Plus } from 'element-plus';
import axios from 'axios';

export default {
    name: 'PostEditComponent',
    components: {
        ElForm,
        ElFormItem,
        ElInput,
        ElButton,
        ElUpload,
        Plus
    },
    props: {
        postId: {
            type: Number,
            required: true,
        },
        countLimit: {
            type: Number,
            default: 3
        }
    },
    data() {
        return {
            postDetail: null,
            postForm: {
                postId: this.postId,
                title: '',
                content: '',
                fileList: [], // 用于显示图片列表
            },
            fileList: [], // 用于存储实际文件对象
        };
    },
    created() {
        this.fetchPostDetails();
    },
    methods: {
        async fetchPostDetails() {
            try {
                const response = await axios.get('/post/postInfo', {
                    params: { postId: this.postId },
                });

                if (response.data.code === 0) {
                    this.postDetail = response.data.data;
                    const postContent = JSON.parse(this.postDetail.postContent);

                    this.postForm.title = this.postDetail.title;
                    this.postForm.content = postContent.content;
                    await this.downloadAndAddFiles(postContent.fileUrlList || []);
                } else {
                    ElMessage.error(`获取动态详情失败：${response.data.message}`);
                }
            } catch (error) {
                console.error('Error fetching post details:', error);
                if (error && error.response) {
                    ElMessage.error(`获取动态详情失败：${error.response.data?.message || error.response.statusText}`);
                } else if (error && error.request) {
                    ElMessage.error('获取动态详情失败：未收到服务器响应');
                } else {
                    ElMessage.error(`获取动态详情失败：${error.message}`);
                }
            }
        },
        async downloadAndAddFiles(urls) {
            const promises = urls.map(async (url) => {
                try {
                    const response = await axios.get('/file/download', { params: { url }, responseType: 'blob' });
                    const file = new File([response.data], url.split('/').pop(), { type: response.data.type });
                    this.fileList.push(file);
                    this.postForm.fileList.push({
                        name: file.name,
                        url: URL.createObjectURL(file),
                        raw: file,
                    });
                } catch (error) {
                    console.error(`Error downloading file from ${url}:`, error);
                }
            });
            await Promise.all(promises);
        },
        handlePictureChange(file, fileList) {
            this.postForm.fileList = fileList;
        },
        handleRemove(file, fileList) {
            this.postForm.fileList = fileList;
            this.fileList = this.fileList.filter(f => f.name !== file.name);
        },
        async submitEditPost() {
            try {
                const formData = new FormData();
                formData.append('postId', this.postForm.postId);
                formData.append('title', this.postForm.title);
                formData.append('content', this.postForm.content);

                this.postForm.fileList.forEach((file) => {
                    if (file.raw) {
                        formData.append('fileList', file.raw);
                    }
                });

                const response = await axios.post('/post/updatePost', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                });
                console.log(response.data);
                if (response.data.code === 0) {
                    ElMessage.success('动态修改成功');
                    this.$emit('post-updated');
                } else {
                    ElNotification({
                        title: '动态发布失败',
                        message: response.data.message || "未知错误",
                        type: 'error',
                        dangerouslyUseHTMLString: true,
                    })
                }
            } catch (error) {
                console.error('Error updating post:', error);
                if (error && error.response) {
                    ElMessage.error(`动态修改失败：${error.response.data?.message || error.response.statusText}`);
                } else if (error && error.request) {
                    ElMessage.error('动态修改失败：未收到服务器响应');
                } else {
                    ElMessage.error(`动态修改失败：${error.message}`);
                }
            }
        },
        cancelEdit() {
            this.$emit('cancel-edit');
        },
    },
};
</script>

<style scoped>
.post-edit-component {
    padding: 20px;
}

.el-upload-list__item {
    width: 100px;
    height: 100px;
}

.title-input {
    box-shadow: none;
    border-radius: 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}

:deep(.el-input__wrapper:hover) {
    box-shadow: none;
}

:deep(.el-input__wrapper:not(:hover)) {
    box-shadow: none;
}

:deep(.el-input__wrapper:focus) {
    box-shadow: none;
}

:deep(.el-textarea__inner) {
    box-shadow: none;
    border-radius: 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}

:deep(.el-textarea__inner:hover) {
    box-shadow: none;
}

:deep(.el-textarea__inner:focus) {
    box-shadow: none;
}
</style>
